package com.idanchuang.count.controller;

import com.idanchuang.component.base.JsonResult;
import com.idanchuang.component.core.util.StringUtil;
import com.idanchuang.count.core.entity.SimpleCountIncrEvent;
import com.idanchuang.count.core.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * TODO 在下一个版本中删除这个测试类
 * @author Richard_yyf
 * @version 1.0 2021/9/26
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Resource
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @PostMapping("/publishEvent2Single")
    public JsonResult<Void> publishEvent2Single(String bizNo, String timestamp) {

        SimpleCountIncrEvent event = mock(bizNo, timestamp);
        String msg = JacksonUtil.toJsonStr(event);
        log.info("test publishEvent2Single, msg: {}", msg);
        kafkaTemplate.send("base_count_single_test", event.getBizNo(), msg);
        return JsonResult.OK;
    }

    @PostMapping("/publishEvent2Batch")
    public JsonResult<Void> publishEvent2Batch(String bizNo, String timestamp) {
        SimpleCountIncrEvent event = mock(bizNo, timestamp);
        String msg = JacksonUtil.toJsonStr(event);
        log.info("test publishEvent2Single, msg: {}", msg);
        kafkaTemplate.send("base_count_batch_test", event.getBizNo(), msg);
        return JsonResult.OK;
    }

    private SimpleCountIncrEvent mock(String bizNo, String timestamp) {
        SimpleCountIncrEvent event = new SimpleCountIncrEvent();
        event.setBizCode("test");
        event.setBizNo(bizNo);
        event.setIncrement(RandomUtils.nextInt(1, 20));
        event.setTime(StringUtil.isBlank(timestamp) ? System.currentTimeMillis()/1000 + "" : timestamp);
        return event;
    }
}
